package com.ruoyi.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.wx.domain.TGoods;
import com.ruoyi.wx.domain.TGoodsCart;
import com.ruoyi.wx.service.ITGoodsCartService;
import com.ruoyi.wx.service.ITGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @Author: wind
 * @CreateTime: 2020-05-04
 * @Description: 购物车
 */


@RestController
@RequestMapping("/api/goodsCart")
public class ApiTgoodsCart {
    @Autowired
    private ITGoodsCartService goodsCartService;
    @Autowired
    private ITGoodsService goodsService;

    /**
     * 购物车列表
     * */
    @RequestMapping("/list")
    public AjaxResult cartList(String userId){

        return AjaxResult.success(goodsCartService.list(new QueryWrapper<>(new TGoodsCart().setUserId(userId))));
    }
    /**
     * 添加到购物车
     * */
    @RequestMapping("/add")
    public AjaxResult add(String goodsId,String userId){
        TGoodsCart tGoodsCart = new TGoodsCart();
        tGoodsCart.setGoodsId(goodsId);
        tGoodsCart.setUserId(userId);
        TGoodsCart goodsCart = goodsCartService.getOne(new QueryWrapper<>(tGoodsCart));
        if (goodsCart!=null){
            goodsCart.setGoodsNum(goodsCart.getGoodsNum()+1);
            goodsCart.setUpdTime(new Date());
            goodsCartService.saveOrUpdate(goodsCart);
        }else {
            TGoods tGoods =goodsService.getOne(new QueryWrapper<>(new TGoods().setGoodsId(goodsId)));
            tGoodsCart.setGoodsName(tGoods.getGoodsName());
            tGoodsCart.setGoodsPrice(tGoods.getGoodsPrice());
            tGoodsCart.setGoodsSmallLogo(tGoods.getGoodsSmallLogo());
            tGoodsCart.setGoodsNum(1);
            tGoodsCart.setGddTime(new Date());
        }

        return AjaxResult.success(goodsCartService.list(new QueryWrapper<>(new TGoodsCart().setUserId(userId))));

    }

    @RequestMapping("/remove")
    public AjaxResult remove(String userId,String goodsId){
        TGoodsCart tGoodsCart = new TGoodsCart();
        tGoodsCart.setGoodsId(goodsId);
        tGoodsCart.setUserId(userId);
        List<TGoodsCart> list = goodsCartService.list(new QueryWrapper<>(tGoodsCart));
        list.forEach(item ->{
            if (item.getGoodsNum() > 1){
                item.setGoodsNum(item.getGoodsNum()-1);
                goodsCartService.saveOrUpdate(item);
            }else{
                goodsCartService.removeById(item.getGoodsCartId());
            }

        });
        return AjaxResult.success(goodsCartService.list(new QueryWrapper<>(new TGoodsCart().setUserId(userId))));
    }


}
